<template>
  <div class="wrap">
    <pro-table
      ref="proTableInst"
      tableTitle="仓库列表"
      :columns="columns"
      :request="fetchWarehousePage"
    >
      <template #operation>
        <n-space>
          <n-button type="primary" @click="handleAddWarehouse">新增</n-button>
        </n-space>
      </template>
    </pro-table>

    <pro-dialog
      v-model:showDialog="warehouseModalShow"
      :modalProps="modalProps"
      :width="1000"
      :showButton="true"
      confirmButtonText="确定"
      cancelButtonText="取消"
      :contentStyle="{ 'padding-left': '10px', 'padding-right': '10px' }"
      :button-loading="confirmLoading"
      @handleConfirm="warehouseConfirm"
      @afterClosed="resetWarehouseForm"
      v-bind="$attrs"
    >
      <pro-form
        ref="warehouseFormInst"
        v-model:form="warehouseForm"
        :formProps="{
          labelPlacement: 'left',
          labelWidth: '100px'
        }"
        :options="warehouseFormOptions"
      ></pro-form>
    </pro-dialog>
  </div>
</template>

<script lang="ts" setup name="Warehouse">
  import { ProTableInst } from '@/components/pro-table/type'
  import { ProFormInst } from '@/components/pro-form/type'
  import {
    useWarehouseApi,
    useWarehouseProForm,
    useWarehouseProTable
  } from './hooks'
  import { WarehouseModel } from '@/api/model/sys/warehouse-model'

  const proTableInst = ref<ProTableInst | null>(null)
  const warehouseFormInst = ref<ProFormInst | null>(null)

  const warehouseModalShow = ref(false)
  const handleType = ref<'add' | 'edit' | ''>('')
  const handleTag = computed(() =>
    handleType.value === 'add' ? '新增仓库' : '修改仓库'
  )
  const modalProps = computed(() => {
    return {
      showIcon: false,
      title: handleTag.value
    }
  })
  const { warehouseForm, resetWarehouseForm, warehouseFormOptions } =
    useWarehouseProForm({ handleType })

  const handleAddWarehouse = () => {
    handleType.value = 'add'
    warehouseModalShow.value = true
  }

  const handleEditWarehouse = (row: WarehouseModel) => {
    warehouseForm.value = row
    handleType.value = 'edit'
    warehouseModalShow.value = true
  }

  const warehouseConfirm = async () => {
    if (await warehouseFormInst.value?.handleSubmit()) {
      fetchAddOrEditWarehouse()
    }
  }

  const {
    fetchWarehousePage,
    fetchAddOrEditWarehouse,
    fetchDelWarehouse,
    confirmLoading
  } = useWarehouseApi({
    handleType,
    handleTag,
    warehouseModalShow,
    warehouseForm,
    proTableInst
  })
  const { columns } = useWarehouseProTable({
    handleEditWarehouse,
    fetchDelWarehouse
  })
</script>

<style lang="less" scoped></style>
